public class Test {

	public int[] getTileFromLatitudeAndLongitude(double latitude,
			double longitude, int zoom) {
		// 将从纬度从-90（南纬）到90（北纬）修正为从0（北纬） 到180（南纬）度。
		// instead of 90(north) to -90(south)
		latitude = 90 - latitude;

		// 将经度修正为从0度到180度
		longitude = 180 + longitude;

		// 在缩放等级zoom 中找到贴图的尺寸
		double latTileSize = 180 / (Math.pow(2, (17 - zoom)));
		double longTileSize = 360 / (Math.pow(2, (17 - zoom)));

		// 找到贴图的坐标
		int tile[] = new int[2];
		tile[0] = (int) (longitude / longTileSize); // X
		tile[1] = (int) (latitude / latTileSize); // Y
		return tile;
	}

	/**
	 * 
	 * 
	 * 
	 * 
	 * @param tileX
	 * @param tileY
	 * @param zoom
	 * @return 返回三个值，分别为中心点的纬度、经度和半径
	 */
	public double[] getParametersFromTile(int tileX, int tileY, int zoom) {
		// 在缩放等级zoom 中找到贴图的尺寸
		double latTileSize = 180 / (Math.pow(2, (17 - zoom)));
		double longTileSize = 360 / (Math.pow(2, (17 - zoom)));

		double lng1 = tileX * longTileSize - 180;
		double lat1 = 90 - tileY * latTileSize;

		double lng2 = (tileX + 1) * longTileSize - 180;
		double lat2 = 90 - (tileY + 1) * latTileSize;

		double latitude = (lat1 + lat2) / 2;
		double longitude = (lng1 + lng2) / 2;
		double radius = getDistanceOfTwoPoints(lat1, lng1, lat2, lng2) / 2;

		double parameters[] = new double[3];
		parameters[0] = latitude;
		parameters[1] = longitude;
		parameters[2] = radius;
		return parameters;
	}

	public double getDistanceOfTwoPoints(double lat1, double lng1, double lat2,
			double lng2) {
		double radLng1 = lng1 * Math.PI / 180.0;
		double radLng2 = lng2 * Math.PI / 180.0;
		double a = radLng1 - radLng2;
		double b = (lat1 - lat2) * Math.PI / 180.0;
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLng1) * Math.cos(radLng2)
				* Math.pow(Math.sin(b / 2), 2))) * 6378.137;
		s = Math.round(s * 1000) / 1000D;
		return s;
	}

	public void test(int zoom, int x, int y) {
		double[] parameters = getParametersFromTile(x, y, zoom);
		System.out.println("Latitude=" + parameters[0] + "\tLongitude="
				+ parameters[1] + "\tRadius=" + parameters[2]);
		for(int i=zoom;i>0;i--){
			System.out.print("--------");
		}
		System.out.println();
		if (zoom > 0) {
			test(zoom - 1, 2 * x, 2 * y);
			test(zoom - 1, 2 * x, 2 * y + 1);
			test(zoom - 1, 2 * x + 1, 2 * y);
			test(zoom - 1, 2 * x + 1, 2 * y + 1);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double lat = 31.90;
		double lng = 118.60;
		int zoom = 3;
		Test t = new Test();
		int[] tile = t.getTileFromLatitudeAndLongitude(lat, lng, zoom);
		System.out.println("TileX=" + tile[0] + "\tTileY=" + tile[1]);
		t.test(zoom, tile[0], tile[1]);
	}

}
